﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Reflection;

namespace Vibz.Common
{
    public class ModelInformation : ModelHandler
    {
        [XmlAttribute("name")]
        public string Name { get; set; }

        public ModelClient Client { get; set; }

        bool allowSingleUser = true;
        [XmlAttribute("allowSingleUser")]
        public bool AllowSingleUser { get { return allowSingleUser; } set { allowSingleUser = value; } }

        bool allowMultiUser = true;
        [XmlAttribute("allowMultiUser")]
        public bool AllowMultiUser { get { return allowMultiUser; } set { allowMultiUser = value; } }

        public ModelInformation()
        { }
        public ModelInformation(string name, string type, string path, List<string> parameters)
        {
            Name = name;
            Type = type;
            Path = path;
            Parameters = parameters;
        }
        public IModelManager Load()
        {
            try
            {
                Assembly asm = System.Reflection.Assembly.LoadFrom(Path);
                if (asm == null)
                    throw new Exception("The model manager does not exists.");

                Type t = asm.GetType(Type);
                if (t == null || !t.GetInterfaces().Contains(typeof(IModelManager)))
                    throw new Exception("The Model manager is not a valid Model type. A model manager should implement IModuleManager.");

                object[] args = Parameters.ToArray<object>();
                return (IModelManager)Activator.CreateInstance(t, args);
            }
            catch (Exception exc)
            {
                throw new Exception("Error loading model manager. " + exc.Message);
            }
        }
    }
    [Serializable]
    [XmlRoot(ElementName = "ModelList")]
    public class ModelInformationList : List<ModelInformation>
    {
        bool allowServerControl = true;
        [XmlAttribute("allowServerControl")]
        public bool AllowServerControl { get { return allowServerControl; } set { allowServerControl = value; } }
    }
    public class ModelClient : ModelHandler { }
    public abstract class ModelHandler
    {
        [XmlAttribute("path")]
        public string Path { get; set; }

        [XmlAttribute("type")]
        public string Type { get; set; }

        public List<string> Parameters { get; set; }
    }
}
